/*
 * Alberto Ruiz-Larrea Guillén...11383
 * Erdi Dogruel..................14955
 * Marcos Pérez Martín...........10324
 */

package com.example.database;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;

//Another way to sort the leaderboard
public class SetTable extends AsyncTask<String, Integer, Long> {

	public SetTable(OpenDB a) {
		open = a;
	}

	@Override
	protected Long doInBackground(String... params) {
		final String name = params[0];
		final String tipo = params[1];

		SQLiteDatabase db = open.getReadableDatabase();

		String[] campos = new String[] { "games_played", "won_matches",
				"draw_matches", "lost_matches" };
		String[] args = new String[] { name };

		Cursor c = db.query("team", campos, "name=?", args, null, null, null);
		int games_played = 0;
		int won_matches = 0;
		int draw_matches = 0;
		int lost_matches = 0;
		int points = 0;
		if (c.moveToFirst()) {
			do {
				games_played = c.getInt(0);
				won_matches = c.getInt(1);
				draw_matches = c.getInt(2);
				lost_matches = c.getInt(3);
			} while (c.moveToNext());
		}
		c.close();

		SQLiteDatabase bd = open.getWritableDatabase();
		ContentValues valores = new ContentValues();

		if (tipo == "1") {
			won_matches = won_matches + 1;
			String wonnew = Integer.toString(won_matches);
			String[] args2 = new String[] { name };
			valores.put("won_matches", wonnew);
			bd.update("leaderboard", valores, "name=?", args2);
		}

		if (tipo == "2") {
			draw_matches = draw_matches + 1;
			String drawnew = Integer.toString(draw_matches);
			String[] args2 = new String[] { name };
			valores.put("draw_matches", drawnew);
			bd.update("leaderboard", valores, "name=?", args2);
		}

		if (tipo == "3") {
			lost_matches = lost_matches + 1;
			String lostnew = Integer.toString(lost_matches);
			String[] args2 = new String[] { name };
			valores.put("lost_matches", lostnew);
			bd.update("leaderboard", valores, "name=?", args2);
		}
		games_played = games_played + 1;
		String games_playednew = Integer.toString(games_played);
		String[] args4 = new String[] { name };
		valores.put("games_played", games_playednew);
		bd.update("leaderboard", valores, "name=?", args4);
		points = 3 * won_matches + draw_matches;
		String pointsnew = Integer.toString(points);
		String[] args3 = new String[] { name };
		valores.put("points", pointsnew);
		bd.update("leaderboard", valores, "name=?", args3);

		return null;
	}

	private OpenDB open;
}
